import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QVBoxLayout,QFileDialog
from PyQt5.QtCore import Qt,QFile
from ui_Apps import Ui_Form
import copy
import os
import subprocess
import logging
class TodoModel(QtCore.QAbstractListModel):
    def __init__(self, todos):
        super().__init__()
        self.todos = copy.copy(todos)
    def data(self, index, role):
        if role == Qt.DisplayRole:
            text = self.todos[index.row()]
            return text
    def rowCount(self, index):
        return len(self.todos)
class DlgApps(QtWidgets.QDialog):
    ui=Ui_Form()
    def __init__(self,arr, parent=None):
        QtWidgets.QDialog.__init__(self, parent) 
        self.ui.setupUi(self)       
        # self.setWindowTitle("方法编号")
        self.model = TodoModel(arr)
        self.ui.todoView.setModel(self.model)
        self.ui.addButton.pressed.connect(self.add)
        self.ui.deleteButton.pressed.connect(self.delete)
        # self.ui.completeButton.pressed.connect(self.complete)
        self.ui.btn_ok.clicked.connect(self.ok)
        self.ui.btn_cancel.clicked.connect(self.cancel)
        self.ui.pushButton_run.clicked.connect(self.run)
    def run(self):
        indexes = self.ui.todoView.selectedIndexes()
        if indexes:
            index = indexes[0]
            self.exec_cmds([self.model.todos[index.row()]])
    def exec_cmds(self,cmds):
        try:
            subprocess.Popen(cmds)
        except FileNotFoundError:
            logging.info("file not found:"+str(cmds))
    def ok(self):
        self.accept()
    def cancel(self):
        self.reject()
    def add(self):
        FileDialog = QFileDialog(self)
        FileDirectory = FileDialog.getOpenFileName(self,'select database file')                #选择目录，返回选中的路径
        logging.info(FileDirectory)
        text=FileDirectory[0]
        if text: # Don't add empty strings.
            # Access the list via the model.
            self.model.todos.append( text)
            # Trigger refresh.        
            self.model.layoutChanged.emit()
            # Empty the input
            self.save()
        
    def delete(self):
        indexes = self.ui.todoView.selectedIndexes()
        if indexes:
            # Indexes is a list of a single item in single-select mode.
            index = indexes[0]
            # Remove the item and refresh.
            del self.model.todos[index.row()]
            self.model.layoutChanged.emit()
            # Clear the selection (as it is no longer valid).
            self.ui.todoView.clearSelection()
            self.save()
    def save(self):
        pass        
if __name__=="__main__":            
    app = QtWidgets.QApplication(sys.argv)
    config_json.read_setting()
    window = DlgArr()
    window.show()
    app.exec()


